package com.developer.datastorage.activity;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.R.integer;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.developer.datastorage.R;
import com.developer.datastorage.util.Util;

public class IntStorageSaveActivity extends AbstractActivity {

	private static final String FILE_NAME = "names";
	private static final String DELIMITER = ",";

	private EditText txtUserName;
	private EditText txtPassword;
	private Button btnSave;
	private Button btnLoad;

	@Override
	public void setLayout() {
		setContentView(R.layout.activity_shared_pref);
	}

	@Override
	public void initializeComponents() {
		txtUserName = (EditText) findViewById(R.id.txt_shared_pref_username);
		txtPassword = (EditText) findViewById(R.id.txt_shared_pref_password);
		btnSave = (Button) findViewById(R.id.btn_shared_pref_save);
		btnLoad = (Button) findViewById(R.id.btn_shared_pref_load);
	}

	@Override
	public void registerEvents() {
		btnSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String name = txtUserName.getText().toString();
				String password = txtPassword.getText().toString();
				FileOutputStream fileOutputStream = null;
				try {
					fileOutputStream = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
					fileOutputStream.write(name.getBytes());
					fileOutputStream.write(DELIMITER.getBytes());
					fileOutputStream.write(password.getBytes());
					fileOutputStream.flush();
					Util.showMessage(IntStorageSaveActivity.this, "Data Saved Successfully");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (fileOutputStream != null) fileOutputStream.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		btnLoad.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				FileInputStream fileInputStream = null;
				try {
					fileInputStream = openFileInput(FILE_NAME);
					StringBuilder stringBuilder = new StringBuilder();
					int c;
					while ((c = fileInputStream.read()) != -1) {
						stringBuilder.append((char) c);
						Log.v("TAG", String.valueOf(c));
					}
					String allFileData = stringBuilder.toString();
					int delimiterIndex = allFileData.indexOf(DELIMITER);
					String username = allFileData.substring(0, delimiterIndex);
					String password = allFileData.substring(delimiterIndex + 1);
					Util.showMessage(IntStorageSaveActivity.this, "Username: " + username + " Password: " + password);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (fileInputStream != null) fileInputStream.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
}
